package com.woniushop.service.imple;

import java.util.List;

import com.woniushop.dao.UserDAO;
import com.woniushop.dao.imple.UserDAOImple;
import com.woniushop.entity.PageBean;
import com.woniushop.entity.User;
import com.woniushop.service.UserService;

/**
 * 用户业务逻辑接口的实现类
 * 
 * @author 崔新雄
 *
 */
public class UserServiceImple implements UserService {

	private UserDAO userDAO = new UserDAOImple();

	/**
	 * 用户登录
	 * 
	 * @param user
	 * @return
	 */
	@Override
	public User login(User user) {
		// 根据账号查询用户数据
		User loginUser = userDAO.findOne(user.getUaccount());
		// 判断密码是否吻合
		if (loginUser != null && loginUser.getUpsw().equals(user.getUpsw())) {
			return loginUser;
		}
		return null;
	}

	/**
	 * 修改登录用户的信息
	 * 
	 * @param loginUser
	 */
	@Override
	public void update(User loginUser) {
		userDAO.update(loginUser);
	}

	/**
	 * 根据条件分页查询用户数据
	 * 
	 * @param pageBean
	 * @param user
	 * @return
	 */
	@Override
	public List<User> findByPage(PageBean pageBean, User user) {
		// 完善pageBean信息
		Integer totalNum = userDAO.count(user);
		pageBean.setTotalNum(totalNum);

		Integer pageSize = pageBean.getPageSize();
		Integer totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1;
		totalPage = totalPage == 0 ? 1 : totalPage;
		pageBean.setTotalPage(totalPage);

		// 如果页码超过范围，则设为最后一页
		if (pageBean.getPage() > totalPage) {
			pageBean.setPage(totalPage);
		}

		// 查询用户数据
		List<User> list = userDAO.findByPage(pageBean.getPage(), pageSize, user);

		pageBean.setNumsOfCurrPage(list.size());

		return list;
	}

	/**
	 * 检查该账号是否被占用
	 * 
	 * @param uaccount
	 * @return trun 没有被占用
	 */
	@Override
	public Boolean checkUaccount(String uaccount) {
		return userDAO.findOne(uaccount) == null;
	}

	/**
	 * 用户注册
	 * 
	 * @param user
	 */
	@Override
	public void reg(User user) {
		user.setUstate(1);
		userDAO.add(user);
	}

	/**
	 * 重置用户密码
	 * 
	 * @param uid
	 */
	@Override
	public void resetUpsw(Integer uid) {
		User user = userDAO.findOne(uid);
		user.setUpsw("000000");
		userDAO.update(user);
	}

	/**
	 * 修改用户状态
	 * 
	 * @param uid
	 * @param ustate
	 */
	@Override
	public void changeUstate(Integer uid, Integer ustate) {
		User user = userDAO.findOne(uid);
		user.setUstate(ustate);
		userDAO.update(user);
	}

	/**
	 * 修改管理员用户角色
	 * 
	 * @param uid
	 * @param urole
	 */
	@Override
	public void changeUrole(Integer uid, Integer urole) {
		User user = userDAO.findOne(uid);
		if (user.getUrole()!=3) {			
			user.setUrole(urole);
			userDAO.update(user);
		}
	}

}
